package symptomsSearch;

import ctm.javacode.dbBean;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Iterator;
import org.json.*;

import java.net.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.BoldStyle;
import jxl.format.Colour;

import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;


@WebServlet("/symptomsSearch/symptomsSearch.do")
public class symptomsSearch extends HttpServlet {

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain");
		response.setCharacterEncoding("UTF-8");
		PrintWriter print = response.getWriter();

		String original_text = request.getParameter("original_text");
		String test_text = request.getParameter("test_text");
		String OriginalSymptomsList = request
				.getParameter("original_text_partial");
		String button_type = request.getParameter("button");

		String str = request.getParameter("str");
		String str2 = request.getParameter("str2");
		
		try {
			String Result = "";

			if (button_type.equals("1")) {

				Result = SymptomsSearch_OriToStd(original_text);
			} else if (button_type.equals("2")) {
				Result = SymptomsSearch_StdToOri(test_text);

			} else if (button_type.equals("3")) {
				Result = SymptomsSearch_keyword(OriginalSymptomsList);

			} else if (button_type.equals("4")) {

				Result = WriteToDatabase(str, str2);

			}else if (button_type.equals("excel")) {

				Result = ExportToExcel(str, str2);

			} else {

				// do nothing

			}

			print.write(Result);
			print.flush();
			print.close();

		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	} // end doPost

	private String SymptomsSearch_OriToStd(String original_text)
			throws NamingException, SQLException, JSONException {
		dbBean db = new dbBean("jdbc/ctmpllab");
		db.Connected();

		/******* 變數宣告 ******/

		// String original_text = "小便清長急。尿赤。小便不利。小便清長。";
		String[] original_text_split_list = original_text.split("。");
		LinkedList<String> list = new LinkedList<String>(); // 儲存排序過後的原始症狀
		Map<String, String> symptom_in_database = new LinkedHashMap<String, String>();// 記錄症狀是否有在資料庫

		String text = "";
		String symptom_in_database_key = "";
		/******* 變數宣告 ******/

		/**** 資料庫的原始症狀依長度排序後，儲存在LinkedList *****/
		String sqlQuery_1 = "select pattern from pattern_to_text_table order by LENGTH(pattern) desc"; // 資料庫原始症狀依長度排序
		ResultSet rs_1;
		rs_1 = db.ExcuteQuery(sqlQuery_1);

		while (rs_1.next()) {
			text = rs_1.getString("pattern");
			list.add(text);

		}
		/**** 資料庫的原始症狀依長度排序後，儲存在LinkedList *****/

		for (int original_text_idx = 0; original_text_idx < original_text_split_list.length; original_text_idx++) {

			boolean if_symptom_in_database = false;

			for (int list_num = 0; (list_num < list.size()); list_num++) {

				String test_pattern = list.get(list_num);
				Pattern pattern = Pattern.compile(test_pattern);
				Matcher matcher = pattern
						.matcher(original_text_split_list[original_text_idx]);

				if (matcher.matches()) {

					if_symptom_in_database = true;
					break;
				}

			}

			if (if_symptom_in_database) {

				symptom_in_database.put(
						original_text_split_list[original_text_idx], "Y");

			} else {

				symptom_in_database.put(
						original_text_split_list[original_text_idx], "N");

			}

		}

		Iterator<String> symptom_in_database_entry = symptom_in_database
				.keySet().iterator();

		JSONArray Data_list = new JSONArray();

		while (symptom_in_database_entry.hasNext()) {

			symptom_in_database_key = symptom_in_database_entry.next();
			JSONObject Data = new JSONObject();
			JSONArray modified_Data_list = new JSONArray();
			if (symptom_in_database.get(symptom_in_database_key).equals("Y")) {

				String sqlQuery = "Select pattern , text from pattern_to_text_table where pattern='"
						+ symptom_in_database_key + "'";
				ResultSet rs;
				rs = db.ExcuteQuery(sqlQuery);

				while (rs.next()) {
					JSONObject modified_Data = new JSONObject();

					modified_Data.put("modified", rs.getString("text"));
					modified_Data_list.put(modified_Data);

				}

			} else {

				JSONObject modified_Data = new JSONObject();

				modified_Data.put("modified", "不存在資料庫");
				modified_Data_list.put(modified_Data);

			}

			Data.put("org", symptom_in_database_key);
			Data.put("modified_Data_list", modified_Data_list);

			Data_list.put(Data);

		}
		db.CloseConn();
		String ResultStandardized = Data_list.toString();
		return ResultStandardized;
	}// end SymptomsSearch_OriToStd
		// ------------------------------------------------------------------------------------------------------------------------------

	private String SymptomsSearch_StdToOri(String test_text)
			throws NamingException, SQLException, JSONException {

		dbBean db = new dbBean("jdbc/ctmpllab");
		db.Connected();
		LinkedList<String> list = new LinkedList<String>();
		String[] buffer = test_text.split("。");

		for (int i = 0; i < buffer.length; i++) {
			list.add(buffer[i]);
			// out.print(buffer[i]+"\n");
		}

		JSONArray modified_Data_list = new JSONArray();

		for (int modified_Data_num = 0; modified_Data_num < list.size(); modified_Data_num++) {

			JSONObject modified_Data = new JSONObject();

			String sqlQuery = "Select * from pattern_to_text_table where text='"
					+ list.get(modified_Data_num) + "'";
			ResultSet rs;
			rs = db.ExcuteQuery(sqlQuery);

			JSONArray Data_list = new JSONArray();
			while (rs.next()) {

				JSONObject Data = new JSONObject();
				Data.put("org", rs.getString("pattern"));
				Data_list.put(Data);
			}
			modified_Data.put("Data_list", Data_list);
			modified_Data.put("modified", list.get(modified_Data_num));
			// modified_Data.put("count",modified_Data_num);
			modified_Data_list.put(modified_Data);
		}

		String ResultOriginal = modified_Data_list.toString();
		db.CloseConn();
		return ResultOriginal;

	}// end SymptomsSearch_StdToOri
		// ------------------------------------------------------------------------------------------------------------------------------

	private String SymptomsSearch_keyword(String OriginalSymptomsList)
			throws NamingException, SQLException, JSONException {

		/******* 變數宣告 ******/

		String[] original_text_list_split = OriginalSymptomsList.split("。"); // 分割後原始症狀陣列
		String original_text;

		JSONArray Data_list = new JSONArray();
		/******* 變數宣告 ******/

		for (int original_text_idx = 0; original_text_idx < original_text_list_split.length; original_text_idx++) {

			LinkedList<String> object = new LinkedList<String>();
			LinkedList<String> attribute_value = new LinkedList<String>();
			/** 單一原始症狀斷詞 **/

			original_text = original_text_list_split[original_text_idx];// 單一原始症狀
			String after_split;

			Segmentation SymptomsSegmentation = new Segmentation();

			after_split = SymptomsSegmentation
					.OutputSegmentationSymptoms(original_text);

			/** 單一原始症狀斷詞 **/

			/****** Keyword屬性分類 ******/

			KeywordAttributeClassification SymptomsAttributeClassification = new KeywordAttributeClassification();

			SymptomsAttributeClassification
					.KeywordAttributeClassification(after_split);

			object = SymptomsAttributeClassification.GetObjectList();

			attribute_value = SymptomsAttributeClassification.GetValueList();

			/****** Keyword屬性分類 ******/

			/****** 屬性查詢 ******/

			List<List<String>> AttributeAndValueList = new ArrayList<List<String>>();
			List<List<String>> ObgectAndAttributeList = new ArrayList<List<String>>();

			AttributeQuery SymptomsAttributeQuery = new AttributeQuery();

			AttributeAndValueList = SymptomsAttributeQuery
					.ValueAttributeQuery(attribute_value);
			ObgectAndAttributeList = SymptomsAttributeQuery
					.ObjectAttributeQuery(object);
			/****** 屬性查詢 ******/

			/****** 可能症狀查詢 ******/
			JSONObject Data = new JSONObject();
			JSONArray modified_Data_list = new JSONArray();

			PossibleSymptoms PossibleSymptomsList = new PossibleSymptoms();
			modified_Data_list = PossibleSymptomsList.PossibleSymptomsQuery(
					AttributeAndValueList, ObgectAndAttributeList);

			Data.put("org", original_text);
			if (modified_Data_list.length() == 0) {
				JSONObject modified_Data = new JSONObject();
				modified_Data.put("modified", "不存在資料庫");
				modified_Data_list.put(modified_Data);
				Data.put("modified_Data_list", modified_Data_list);

			} else {
				Data.put("modified_Data_list", modified_Data_list);
			}
			Data_list.put(Data);
			/****** 可能症狀查詢 ******/
		}

		String ResultPossibleStandardized = Data_list.toString();
		return ResultPossibleStandardized;

	}// end SymptomsSearch_keyword

	// ------------------------------------------------------------------------------------------------------------------------------

	private static String WriteToDatabase(String a, String b)
			throws NamingException, SQLException {
		dbBean db = new dbBean("jdbc/ctmpllab");
		db.Connected();
		// 小便清長急。尿赤。小便不利。小便清長。
		String[] ori = a.split("\n");
		String[] standard_list = b.split("\n");
		LinkedList<Integer> symptoms_list_index = new LinkedList<Integer>();

		for (int i = 0; i < ori.length; i++) {

			String sqlQuery_if_symptoms_exist = "Select * from un_confirm_symptoms where symptom ='"
					+ ori[i].substring(0, ori[i].length() - 1) + "'";
			ResultSet if_symptoms_exist;
			if_symptoms_exist = db.ExcuteQuery(sqlQuery_if_symptoms_exist);

			if (!if_symptoms_exist.next()) {

				symptoms_list_index.add(i);
			}

		}

		for (int j = 0; j < symptoms_list_index.size(); j++) {

			int index = symptoms_list_index.get(j);

			String sqlQuery_insert_to_database = "INSERT INTO un_confirm_symptoms (symptom,standard_symptoms) VALUE ('"
					+ ori[index].substring(0, ori[index].length() - 1)
					+ "','"
					+ standard_list[index] + "')";

			try {
				db.ExcuteUpdate(sqlQuery_insert_to_database);

			} catch (SQLException e) {
				throw new SQLException(e);
			} // end try-catch
		}
		db.CloseConn();
		return "success";

		

	}

	// ------------------------------------------------------------------------------------------------------------------------------

	private static String ExportToExcel(String a, String b)
			throws NamingException, SQLException, WriteException, IOException {

		String[] ori = a.split("\n");
		String[] standard_list = b.split("\n");

		WritableWorkbook workbook = Workbook.createWorkbook(new File(
				"C:\\Users\\pllab\\Desktop\\test.xls"));

		WritableSheet sheet = workbook.createSheet("My Sheet", 0);

		WritableFont myFont = new WritableFont(WritableFont.createFont("標楷體"),
				14);
		myFont.setColour(Colour.BLACK);

		WritableFont titleFont = new WritableFont(
				WritableFont.createFont("標楷體"), 14);
		titleFont.setColour(Colour.BLACK);
		titleFont.setBoldStyle(WritableFont.BOLD);

		WritableCellFormat cellFormat = new WritableCellFormat();
		WritableCellFormat titleFormat = new WritableCellFormat();

		cellFormat.setFont(myFont); // 指定字型
		titleFormat.setFont(titleFont);
		titleFormat.setBackground(Colour.GRAY_25); //
		titleFormat.setAlignment(Alignment.CENTRE); // 對齊方式

		Label label00 = new Label(0, 0, "原始症狀", titleFormat);
		sheet.addCell(label00);
		Label label10 = new Label(1, 0, "標準症狀", titleFormat);
		sheet.addCell(label10);

		for (int i = 0; i < ori.length; i++) {
			Label label01 = new Label(0, i + 1, ori[i], cellFormat);
			sheet.addCell(label01);
		}

		for (int j = 0; j < standard_list.length; j++) {

			Label label11 = new Label(1, j + 1, standard_list[j], cellFormat);
			sheet.addCell(label11);

		}

		workbook.write();
		workbook.close();

		return "success";

	}
	

}
